<template>
  <div>

    <!--    搜索栏开始-->
    <el-form :inline="true" ref="searchData" :model="searchData" label-width="80px">

      <el-form-item label="仓库">
        <el-select v-model="searchData.storehouseSearch"  multiple
                   @change="changeOptions('storehouse','nameOptions','search')" placeholder="请选择">
          <el-option
            v-for="item in storehouseOptions"
            :key="item.value"
            :label="item.value"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="名称">
        <el-select v-model="searchData.nameSearch"  multiple
                   @change="changeOptions('name','standardsOptions','search')" placeholder="请选择">
          <el-option
            v-for="item in nameOptions"
            :key="item.value"
            :label="item.value"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="规格">
        <el-select v-model="searchData.standardsSearch" multiple
                   @change="changeOptions('standards','glossOptions','search')" placeholder="请选择">
          <el-option
            v-for="item in standardsOptions"
            :key="item.value"
            :label="item.value"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="光泽度">
        <el-select v-model="searchData.glossSearch"  multiple
                   @change="changeOptions('gloss','typeOptions','search')" placeholder="请选择">
          <el-option
            v-for="item in glossOptions"
            :key="item.value"
            :label="item.value"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="种类">
        <el-select v-model="searchData.typeSearch"  multiple placeholder="请选择">
          <el-option
            v-for="item in typeOptions"
            :key="item.value"
            :label="item.value"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="记录种类">
        <el-select v-model="searchData.recordType" clearable placeholder="请选择">
          <el-option
            v-for="item in recordTypeOptions"
            :key="item.key"
            :label="item.key"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="记录时间">
        <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="请开始选择时间"
                        v-model="searchData.startDate"></el-date-picker>
        -
        <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="请结束选择时间"
                        v-model="searchData.endDate"></el-date-picker>
      </el-form-item>

      <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="Search">搜索</el-button>
            <el-button type="primary" icon="el-icon-remove" @click="onReset">重置</el-button>
      </el-form-item>

      <el-form-item style=" margin-left:300px">
        <el-tabs type="card" @tab-click="changeView" >
          <el-tab-pane label="统计图" name="chart"></el-tab-pane>
          <el-tab-pane label="表格" name="table"></el-tab-pane>
        </el-tabs>
      </el-form-item>

    </el-form>


    <!--搜索栏结束-->
    <div id="chart"
         v-show="!tableView"
    >
      <el-row>
        <el-col :span="12">
          <highcharts id="high" class="high" :options="option" :callback="myCallback" ></highcharts>
        </el-col>
        <el-col :span="12">
          <highcharts id="high2" class="high2" :options="option2"></highcharts>
        </el-col>
      </el-row>
    </div>
<div id="table"
v-show="tableView">
  <!--    数据表格-->
  <el-table
    :data="tableData"
    style="width: 100%">
    <el-table-column label="编号" width="180" prop="id"></el-table-column>
    <el-table-column label="仓库" prop="storehouse"></el-table-column>
    <el-table-column label="名称" width="180" prop="name"></el-table-column>
    <el-table-column label="规格" prop="standards"></el-table-column>
    <el-table-column label="光泽度" prop="gloss"></el-table-column>
    <el-table-column label="种类" prop="type"></el-table-column>
    <el-table-column label="记录" prop="record"></el-table-column>
    <el-table-column label="记录时间" prop="date"></el-table-column>

<!--    上传和下载-->
    <el-table-column align="right">
      <template slot="header" slot-scope="scope">
        <el-button type="primary" icon="el-icon-upload" circle @click="uploadFile"></el-button>
        <el-button type="primary" icon="el-icon-download" circle @click="exportExcel"></el-button>
      </template>
      <!--      编辑和删除按钮-->
      <template slot-scope="scope">
        <el-button
          size="mini"
          @click="handleEdit(scope.$index, scope.row)">编辑
        </el-button>
        <template>
          <el-popconfirm
            confirm-button-text='好的'
            cancel-button-text='不用了'
            icon="el-icon-info"
            icon-color="red"
            @confirm="handleDelete(scope.$index, scope.row)"
            title="确定删除吗？"
          >
            <el-button
              slot="reference"
              size="mini"
              type="danger">删除
            </el-button>
          </el-popconfirm>
        </template>
      </template>
    </el-table-column>
  </el-table>

  <!--添加记录的按钮-->
  <el-row>
    <el-col :span="4">
      <el-button type="success" @click="addRecord" size="small"> 添加</el-button>
    </el-col>

    <!--分页功能-->
    <el-col :span="10" :push="10">
      <el-pagination
        layout="prev, pager, next, jumper, ->,total,sizes"
        background
        :current-page="searchData.currentPage"
        :page-sizes="[2,4,6,8]"
        :page-size="searchData.pageSize"
        @size-change="changeSize"
        @current-change="currentChange"
        :total="searchData.total">
      </el-pagination>
    </el-col>
  </el-row>
</div>

<!--上传文件的对话框-->
    <el-dialog
      title="上传文件"
      :visible.sync="uploadVisible"
      width="30%"
    >
      <el-upload
        class="upload"
        ref="upload"
        action=""
        :file-list="fileList"
        :before-upload="handleBeforeUpload"
        :http-request="handleFileUploadSubmit"
        :on-change="handleFileListChanged"
        :on-remove="removeFile"
        :auto-upload="false">
        <el-button slot="trigger" size="small" type="primary" >选取文件</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" @click="downloadTemplate">下载模板</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
        <div slot="tip" class="el-upload__tip">只能上传Excel文件</div>
      </el-upload>
    </el-dialog>
    <!--    编辑和添加的对话框，里面是一个表单-->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="30%"
    >
      <el-form ref="form" :rules="rules" :model="form" label-width="80px">
        <el-form-item label="仓库" prop="storehouse">
          <!--            <el-input v-model="form.storehouse"></el-input>-->
          <el-select v-model="form.storehouse" :disabled="selectable" placeholder="请选择" @change="changeOptions('storehouse','nameOptions','form')">
            <el-option
              v-for="item in storehouseOptions"
              :key="item.value"
              :label="item.value"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-select v-model="form.name" :disabled="selectable"  placeholder="请选择" @change="changeOptions('name','standardsOptions','form')">
            <el-option
              v-for="item in nameOptions"
              :key="item.value"
              :label="item.value"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="规格" prop="standards">
          <el-select v-model="form.standards" :disabled="selectable"  placeholder="请选择" @change="changeOptions('standards','glossOptions','form')">
            <el-option
              v-for="item in standardsOptions"
              :key="item.value"
              :label="item.value"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="光泽度" prop="gloss">
          <el-select v-model="form.gloss" :disabled="selectable"  placeholder="请选择" @change="changeOptions('gloss','typeOptions','form')">
            <el-option
              v-for="item in glossOptions"
              :key="item.value"
              :label="item.value"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="种类" prop="type">
          <el-select v-model="form.type" :disabled="selectable" @change="handleChange" placeholder="请选择" >
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.value"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="记录种类" prop="recordType">
          <el-select v-model="form.recordType" placeholder="请选择">
            <el-option
              v-for="item in formRecordTypeOptions"
              :key="item.key"
              :label="item.key"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="记录" prop="record">
          <el-input v-model.number="form.record"></el-input>
        </el-form-item>

        <el-form-item label="记录时间" prop="date">
          <el-date-picker type="datetime" value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择时间" v-model="form.date" style="width: 100%;"></el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onSave('form')">保存</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
  import { Chart } from "highcharts-vue";
  export default {
    name: "NumRecord",
    components:{
      highcharts: Chart,
    },
    data() {

      return {
        tableView:false,
        selectable:false,
        dialogVisible: false,
        uploadVisible:false,
        dialogTitle: '',
        quickSearch: '',
        fileList:[],
        storehouseOptions: [],
        nameOptions: [],
        standardsOptions: [],
        glossOptions: [],
        typeOptions: [],
        formRecordTypeOptions: [{key: '流水记录', value: 2}, {key: '库存记录', value: 3}],
        recordTypeOptions: [{key: "进货记录", value: 0}, {key: '出货记录', value: 1},{key: '流水记录', value: 2}, {key: '库存记录', value: 3}],
        searchData: {
          storehouseSearch: [],
          nameSearch: [],
          standardsSearch: [],
          recordType: [],
          glossSearch: [],
          typeSearch: [],
          startDate: '',
          endDate: '',
          pageSize: 2,
          currentPage: 1,
          total: 1,
        },
        chartData:[{
        name: 'Chrome',
        y: 61.41,
        // sliced: true,
        // selected: true
      }, {
        name: 'Internet Explorer',
        y: 11.84
      }, {
        name: 'Firefox',
        y: 10.85
      }, {
        name: 'Edge',
        y: 4.67
      }, {
        name: 'Safari',
        y: 4.18
      }, {
        name: 'Sogou Explorer',
        y: 1.64
      }, {
        name: 'Opera',
        y: 1.6
      }, {
        name: 'QQ',
        y: 1.2
      }, {
        name: 'Other',
        y: 2.61
      }],
        // chart数据
        option: {
          chart: {
            plotBackgroundColor: null,
            plotBorderWidth: null,
            plotShadow: false,
            type: 'pie'
          },
          title: {
            text: '2018年1月浏览器市场份额'
          },
          tooltip: {
            pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
          },
          plotOptions: {
            pie: {
              allowPointSelect: true,
              cursor: 'pointer',
              dataLabels: {
                enabled: true,
                format: '<b>{point.name}</b>: {point.percentage:.1f} %',
                style: {
                  // color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
                }
              }
            }
          },
          series: [{
            name: 'Brands',
            colorByPoint: true,
            data: [],
          }]
        },
        option2:{
          title: {
            text: '2010 ~ 2016 年太阳能行业就业人员发展情况'
          },
          subtitle: {
            text: '数据来源：thesolarfoundation.com'
          },
          yAxis: {
            title: {
              text: '就业人数'
            }
          },
          legend: {
            layout: 'vertical',
            align: 'right',
            verticalAlign: 'middle'
          },
          plotOptions: {
            series: {
              label: {
                connectorAllowed: false
              },
              pointStart: 2015
            }
          },
          series: [{
            name: '安装，实施人员',
            data: [43934, 52503, 57177, 69658, 97031, 119931, 137133]
          }, {
            name: '工人',
            data: [24916, 24064, 29742, 29851, 32490, 30282, 38121]
          }, {
            name: '销售',
            data: [11744, 17722, 16005, 19771, 20185, 24377, 32147]
          }, {
            name: '项目开发',
            data: [null, null, 7988, 12169, 15112, 22452, 34400]
          }, {
            name: '其他',
            data: [11744, 17722, 16005, 19771, 20185, 24377, 32147],
          }],
          responsive: {
            rules: [{
              condition: {
                maxWidth: 500
              },
              chartOptions: {
                legend: {
                  layout: 'horizontal',
                  align: 'center',
                  verticalAlign: 'bottom'
                }
              }
            }]
          }
          },
        tableData: [],
        // 编辑和添加的表单数据
        form: {},
        // 添加或编辑时验证
        rules: {
          storehouse: [{required: true, message: '此项不能为空', trigger: 'blur'}],
          name: [{required: true, message: '此项不能为空', trigger: 'blur'}],
          standards: [{required: true, message: '此项不能为空', trigger: 'blur'}],
          gloss: [{required: true, message: '此项不能为空', trigger: 'blur'}],
          type: [{required: true, message: '此项不能为空', trigger: 'blur'}],
          recordType: [{required: true, message: '此项不能为空', trigger: 'blur'}],
          record: [{required: true, message: '此项不能为空', trigger: 'blur'},
            {type: 'number', message: '必须为数字'}
          ],
          date: [{required: true, message: '此项不能为空', trigger: 'blur'}],
        },
      }
    },
    methods: {
      myCallback(){
        this.option.series[0].data= this.chartData;
      },
      // 测试切换图表
      changeView(tab){
        this.tableView = tab.name === "table";
        },
      // 删除上传文件列表时的操作
      removeFile(file){
        this.fileList.splice(this.fileList.indexOf(file),1);
      },
      uploadFile(){
        // 待上传的文件列表清空
        this.fileList = [];
        this.uploadVisible = true;
      },
      downloadTemplate(){
        this.$http({ // 用axios发送post请求
          method: 'post',
          url: '/downloadTemplate', // 请求地址
          responseType: 'blob' // 表明返回服务器返回的数据类型
        })
          .then((resp) => { // 处理返回的文件流
            if (!resp) {
              return
            }
            let url = window.URL.createObjectURL(new Blob([resp.data])) // 这里一定要使用resp.data的内容，否则excel中的内容为: [object][object], 而非实际的模板内容
            let link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            link.setAttribute('download', '石材记录模板.xls')

            document.body.appendChild(link)
            link.click()
          })
      },
      /**
       * 文件状态改变时的操作
       * @param {Object} selectedFile 选择的文件对象
       * */
      handleFileListChanged(selectedFile) {
        // TODO 选择了文件时可以做一些文件类型的校验之类的操作
        // 文件列表修改为选择的文件
        this.fileList.push(selectedFile);
        console.log(this.fileList);
      },

      /**
       * 点击【上传】按钮时要进行的操作
       * */
      submitUpload() {
        // TODO 还可以进行文件校验等操作
        if (this.fileList.length < 1) {
          this.$alert('请选择文件后再上传！', '提示', {
            type: 'warning'
          });
          return;
        }
        // 校验无误将要上传，这里会调用 http-request 所绑定的方法
        this.$refs.upload.submit();
        this.fileList = [];
      },
      // 上传前校验
      handleBeforeUpload(file) {
        let extension = file.name.split(".")[1];
        let extensionList = ["xls", "xlsx"];
        if (extensionList.indexOf(extension) < 0) {
          this.$message.warning("只能上传Excel文件");
          return false;
        }
      },
      /**
       * 发送文件上传的网络请求
       * */
      handleFileUploadSubmit( {file} ) {
        // 将进度条的颜色重置为蓝色
        this.progressColor = 'rgb(0, 0, 255)';
        // 创建一个表单，用于存放请求数据(主要是文件)
        const fileFormData = new FormData();
        // 在表单中添加要发送给接口的数据
        fileFormData.append('username', 'Alice');
        fileFormData.append('excelFile', file);
        // 使用 axios 发送文件上传请求，并监听文件上传进度
        this.$http.post('/upload', fileFormData).then((res) => {
          if (res.data.status){
            this.$message({
              message: "恭喜你，" + res.data.message,
              type: 'success'
            });
          }else {
            console.log(res.data.message);
            this.$alert('上传失败！'+res.data.message, '提示', {type: 'error'});
          }
        }).catch(error => {
          // 请求失败，将进度条置为红色
          this.$alert('上传失败！', '提示', {type: 'error'});
          console.error(error);
        });
      },

      //导出Excel
      exportExcel() {
        require.ensure([], () => {
          const { export_json_to_excel } = require('../../excel/Export2Excel');
          //设置Excel表格第一行的标题
          const tHeader = ['编号', '仓库', '规格', '光泽度', '名称', '种类', '记录', '时间'];
          //设置标题对应的字段
          let filterVal = ['id', 'storehouse', 'standards', 'gloss', 'name', 'type', 'record', 'date'];
          //把后台传过来的数据存到list
          const list = this.tableData;
          const data = this.formatJson(filterVal, list);
          export_json_to_excel(tHeader, data, '石材记录统计');
        })
      },
      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => v[j]))
      },

      // 添加的表单最后type选择后无法显示在选择框里，需要手动刷新
      handleChange(){
        this.$forceUpdate()
      },
      // 搜索值改变时触发的方法
      changeOptions(change,search,type) {
        if (change==='storehouse') {
          // 下拉框清空
          this.nameOptions = [];
          this.standardsOptions = [];
          this.glossOptions = [];
          this.typeOptions = [];
          // 选择的内容清空
          this.searchData.nameSearch = [];
          this.searchData.standardsSearch = [];
          this.searchData.glossSearch = [];
          this.searchData.typeSearch = [];
          // form选择的内容清空
          this.form.name = null;
          this.form.standards = null;
          this.form.gloss = null;
          this.form.type = null;
        } else if (change==='name') {
          this.standardsOptions = [];
          this.glossOptions = [];
          this.typeOptions = [];
          this.searchData.standardsSearch = [];
          this.searchData.glossSearch = [];
          this.searchData.typeSearch = [];
          this.form.standards = null;
          this.form.gloss = null;
          this.form.type = null;
        } else if (change==='standards') {
          this.glossOptions = [];
          this.typeOptions = [];
          this.searchData.glossSearch = [];
          this.searchData.typeSearch = [];
          this.form.gloss = null;
          this.form.type = null;
        } else if (change==='gloss') {
          this.typeOptions = [];
          this.searchData.typeSearch = [];
          this.form.type = null;
        }
        // 重新搜索下拉框
        this.searchOptions(search,type);
      },
      // 搜索下拉框方法
      searchOptions(key,type) {
        // 搜索栏下拉框，多选
        if (type ==='search'){
          if (key === '' && this.searchData.storehouseSearch.length === 0) {
            this.$http.post("/searchOptions", this.searchData).then(res => {
              this.storehouseOptions = res.data;
            })
          } else if (key === 'nameOptions' && this.searchData.nameSearch.length===0 && this.searchData.storehouseSearch.length > 0) {
            this.$http.post("/searchOptions", this.searchData).then(res => {
              this.nameOptions = res.data;
            })
          } else if (key === 'standardsOptions' && this.searchData.standardsSearch.length===0 && this.searchData.nameSearch.length > 0) {
            this.$http.post("/searchOptions", this.searchData).then(res => {
              this.standardsOptions = res.data;
            })
          } else if (key === 'glossOptions' && this.searchData.glossSearch.length===0 && this.searchData.standardsSearch.length > 0) {
            this.$http.post("/searchOptions", this.searchData).then(res => {
              this.glossOptions = res.data;
            })
          } else if (key === 'typeOptions' && this.searchData.typeSearch.length===0 && this.searchData.glossSearch.length > 0) {
            this.$http.post("/searchOptions", this.searchData).then(res => {
              this.typeOptions = res.data;
            })
          }
        }
        // 表单下拉框，单选
        else if (type ==='form'){
          if (key === '' && this.form.storehouse === '') {
            this.$http.post("/formOptions", this.form).then(res => {
              this.storehouseOptions = res.data;
            })
          } else if (key === 'nameOptions'  && this.form.storehouse !== '') {
            this.$http.post("/formOptions", this.form).then(res => {
              this.nameOptions = res.data;
            })
          } else if (key === 'standardsOptions'  && this.form.name  !== '') {
            this.$http.post("/formOptions", this.form).then(res => {
              this.standardsOptions = res.data;
            })
          } else if (key === 'glossOptions'  && this.form.standards  !== '') {
            this.$http.post("/formOptions", this.form).then(res => {
              this.glossOptions = res.data;
            })
          } else if (key === 'typeOptions' && this.form.gloss  !== '') {
            this.$http.post("/formOptions", this.form).then(res => {
              this.typeOptions = res.data;
            })
          }
        }

      },

//重置搜索条件方法
      onReset(){
        // 下拉框清空
        this.nameOptions = [];
        this.standardsOptions = [];
        this.glossOptions = [];
        this.typeOptions = [];
        // 选择的内容清空
        this.searchData.storehouseSearch=[];
        this.searchData.nameSearch = [];
        this.searchData.standardsSearch = [];
        this.searchData.glossSearch = [];
        this.searchData.typeSearch = [];
      },
      // 搜索按钮，将当前页调为1
      Search(){
        this.searchData.currentPage=1
        this.form.recordType = JSON.parse(JSON.stringify(this.searchData.recordType));
        this.onSearch();
      },
      // 搜索方法
      onSearch() {
        this.$http.post("/searchRecordData", this.searchData).then(res => {
          this.tableData = res.data.data;
          this.searchData.total = res.data.total;
        });
      },
      // 添加和编辑的取消按钮方法
      cancel() {
        this.form = {};
        this.dialogVisible = false;
      },
      // 添加记录
      addRecord() {
        this.selectable = false;
        this.dialogVisible = true;
        this.dialogTitle = "添加记录";
        this.form =  {}

      },
      // 改变当前页时触发的方法
      currentChange(page) {
        this.searchData.currentPage = page;
        this.onSearch();

      },
      // 改变每页显示条数时触发的方法
      changeSize(size) {
        this.searchData.currentPage = 1;
        this.searchData.pageSize = size;
        this.onSearch();

      },
      // 保存方法
      onSave(formName) {

        this.$refs[formName].validate((valid) => {
          console.log(this.form);
          if (valid) {
            this.$http.post("/saveRecordData", this.form).then(res => {
              if (res.data.status) {
                this.$message({
                  message: '恭喜你' + res.data.message,
                  type: 'success'
                });
                this.form = {};
                this.dialogVisible = false;
                this.searchData.currentPage=1;
                this.onSearch();
              } else {
                this.$message.error(res.data.message);
              }
            });
          } else {
            this.$message.error('请正确输入后再试！');
            return false;
          }
        });

      },
      // 编辑方法
      handleEdit(index, row) {
        this.selectable = true;
        this.dialogVisible = true;
        this.dialogTitle = '编辑记录';
        this.form = JSON.parse(JSON.stringify(row));

      },

      // 删除方法
      handleDelete(index, row) {
        this.form.id = JSON.parse(JSON.stringify(row.id));
        console.log(this.form);
        this.$http.post("/deleteRecordData", this.form).then(res => {
          if (res.data.status) {
            this.$message({
              message: "恭喜你" + res.data.message,
              type: 'success'
            });
            this.searchData.currentPage=1;
            this.onSearch();
          } else {
            this.$message.error(res.data.message);
          }
        })
      },

    },
    created() {

      this.searchOptions('', 'search');

    }
  }
</script>

<style scoped>

</style>
